package com.yupi.ojsystem.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.ojsystem.common.ErrorCode;
import com.yupi.ojsystem.constant.CommonConstant;
import com.yupi.ojsystem.exception.BusinessException;
import com.yupi.ojsystem.exception.ThrowUtils;
import com.yupi.ojsystem.judge.codesandbox.JudgeService;
import com.yupi.ojsystem.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.yupi.ojsystem.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.yupi.ojsystem.model.entity.Question;
import com.yupi.ojsystem.model.entity.QuestionSubmit;
import com.yupi.ojsystem.mapper.QuestionSubmitMapper;
import com.yupi.ojsystem.model.entity.User;
import com.yupi.ojsystem.model.enums.QuestionSubmitLanguageEnum;
import com.yupi.ojsystem.model.enums.QuestionSubmitStatusEnum;
import com.yupi.ojsystem.model.vo.QuestionSubmitVO;
import com.yupi.ojsystem.service.IQuestionService;
import com.yupi.ojsystem.service.IQuestionSubmitService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.ojsystem.service.UserService;
import com.yupi.ojsystem.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * <p>
 * 题目提交 服务实现类
 * </p>
 *
 * @author k
 * @since 2025-04-04
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit> implements IQuestionSubmitService {

    @Resource
    IQuestionService questionService;
    @Resource
    UserService userService;
    @Resource
    @Lazy
    JudgeService judgeService;
    /**
     * 提交题目
     * @param questionSubmitAddRequest 题目提交信息
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        if(questionSubmitAddRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String language = questionSubmitAddRequest.getLanguage();
        ThrowUtils.throwIf(ObjectUtil.isEmpty(language), ErrorCode.PARAMS_ERROR,"未选择编程语言");
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        ThrowUtils.throwIf(languageEnum==null,ErrorCode.PARAMS_ERROR,"不支持的编程语言");
        String code = questionSubmitAddRequest.getCode();
        ThrowUtils.throwIf(ObjectUtil.isEmpty(code),ErrorCode.PARAMS_ERROR,"未填写代码");
        Long questionId = questionSubmitAddRequest.getQuestionId();
        //判断题目是否存在
        Question question = questionService.getById(questionId);
        ThrowUtils.throwIf(question==null,ErrorCode.NOT_FOUND_ERROR,"该题目不存在");
        Long userId = loginUser.getId();
        //加入数据库
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setLanguage(language);
        questionSubmit.setCode(code);
        questionSubmit.setJudgeInfo("{}");
        //先将状态设置为等待中
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setUserId(userId);
        boolean save = this.save(questionSubmit);
        if(!save){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"提交失败");
        }
        Long questionSubmitId = questionSubmit.getId();
        //执行判题服务
        CompletableFuture.runAsync(() -> {
            judgeService.doJudge(questionSubmitId);
        });
        return questionSubmitId;
    }

    /**
     * 构造提交查询条件
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        //构造条件
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status)!=null, "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        //仅本人和管理员能看见自己的答案
        Long userId = loginUser.getId();
        //处理脱敏
        if(!Objects.equals(userId, questionSubmit.getUserId()) &&!userService.isAdmin(loginUser)){
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit ->
                getQuestionSubmitVO(questionSubmit, loginUser)
        ).collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

    @Override
    public int doQuestionSubmitInner(long questionId, long userId) {
        return 0;
    }
}
